import 'dart:async';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/song_card.dart';
import 'package:flutter_application_1/models/song_model.dart';
import 'package:flutter_application_1/services/song_service.dart';

class SongPage extends StatefulWidget {
  const SongPage({Key? key}) : super(key: key);

  @override
  _SongPageState createState() => _SongPageState();
}

class _SongPageState extends State<SongPage>
    with AutomaticKeepAliveClientMixin {
  late EasyRefreshController _controller;
  List<SongItem> _songList = SongList([]).list;
  int page = 1;
  int limit = 10;
  bool hasMore = true;
  bool error = false;
  String errorMsg = '';
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController(
        controlFinishLoad: true, controlFinishRefresh: true);
    _getSong();
  }

  Future _getSong({bool push = false}) async {
    List<dynamic> result = await SongService.getSongs(page: page);
    SongList songListModel = SongList.fromJson(result);
    setState(() {
      //hasMore
      page++;
      if (push) {
        _songList.addAll(songListModel.list);
      } else {
        _songList = songListModel.list;
      }
    });
  }

  FutureOr _onRefresh() async {
    page = 1;
    await _getSong();
    _controller.finishRefresh();
    _controller.resetFooter();
  }

  FutureOr _onLoad() async {
    await _getSong(push: true);
    _controller.finishLoad();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      controller: _controller,
      header: ClassicHeader(),
      footer: ClassicFooter(),
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: ListView.builder(
        itemCount: _songList.length,
        itemBuilder: (BuildContext context, int index) {
          return Column(
            children: [
              SizedBox(
                height: 8,
              ),
              SongCard(
                songItem: _songList[index],
              ),
            ],
          );
        },
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
